<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告条 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeStepsIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab栏 -->
      <el-form
        :model="addGoodsForm"
        :rules="addGoodsFormRules"
        ref="addGoodsFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeStepsIndex"
          tab-position="left"
          :before-leave="beforeTabsLeave"
          @tab-click="tabsClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="addGoodsForm.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="addGoodsForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="addGoodsForm.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyParamsList"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals2">
                <el-checkbox
                  :label="item_val"
                  v-for="(item_val, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyParmasList"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 上传图片 -->
            <el-upload
              :action="uploadImgURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
              :headers="headersReq"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本 -->
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="addGoodsBtn" @click="addGoods">
              添加商品
            </el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 预览图片对话框 -->
      <el-dialog
        title="预览图片"
        :visible.sync="previewDialogVisible"
        width="50%"
      >
        <img :src="pathPreview" alt="" style="width:100%" />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// 导入lodash
import _ from 'lodash'

export default {
  data() {
    return {
      // 步骤条当前索引
      activeStepsIndex: 0,
      // 添加商品 数据对象
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 级联选择器选中的id值
        goods_cat: [],
        // 需要上传保存到服务器的图片
        pics: [],
        // 富文本输入的商品介绍
        goods_introduce: '',
        // 选中的商品参数
        attrs: []
      },
      // 添加商品校验规则
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      // 商品分类列表
      cateList: [],
      // 级联选择器配置对象
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 动态参数列表
      manyParamsList: [],
      // 静态属性列表
      onlyParmasList: [],
      // 上传图片url地址
      uploadImgURL: 'http://127.0.0.1:8899/api/private/v1/upload',
      // 设置上传的请求头
      headersReq: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片路径
      pathPreview: '',
      // 预览图片对话框显示隐藏
      previewDialogVisible: false
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取商品分类列表失败！')
      this.cateList = res.data
    },
    // 级联选择器选中状态改变事件
    handleChange() {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
        this.$message.warning('只能选择三级商品分类！')
        return
      }
    },
    // tabs 页签发生切换时触发事件
    beforeTabsLeave(activeName, oldActiveName) {
      // activeName 即将要去的tab页签
      // oldActiveName 之前的tab页签
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类！')
        return false
      }
    },
    // tabs 页签被选中时触发
    async tabsClicked() {
      if (this.activeStepsIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        if (res.meta.status !== 200)
          return this.$message.error('获取参数列表失败！')
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.attr_vals2 = []
        })
        this.manyParamsList = res.data
      } else if (this.activeStepsIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' }
          }
        )
        if (res.meta.status !== 200)
          return this.$message.error('获取参数列表失败！')
        this.onlyParmasList = res.data
      }
    },
    // 预览图片事件
    handlePreview(file) {
      // 将需要预览的图片的真实url地址保存下来 等待提供给img标签指向的url
      this.pathPreview = file.response.data.url.replace(/8888/g, '8899')
      this.previewDialogVisible = true
    },
    // 删除图片事件
    handleRemove(file) {
      // 先拿到用户点击删除的那张图片的临时地址
      const filePath = file.response.data.tmp_path
      // 然后循环遍历当前pics数组里的每一个对象 对照它们的临时地址 如果相同返回ture 拿到当前的索引号
      const index = this.addGoodsForm.pics.findIndex(
        item => item.pic === filePath
      )
      // 拿到索引以后 利用splice方法删除对应的图片
      this.addGoodsForm.pics.splice(index, 1)
    },
    // 图片上传成功事件
    handleSuccess(res) {
      // 把上传成功后返回的临时地址保存到addGoodsForm中
      const pathURL = {
        pic: res.data.tmp_path
      }
      this.addGoodsForm.pics.push(pathURL)
    },
    // 添加商品
    addGoods() {
      // 首先进行表单的预校验
      this.$refs.addGoodsFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整的信息！')
        // 发起请求之前需要处理两项数据
        // goods_cat 必须是以','分割的分类列表
        // attrs 商品的参数（数组），包含 `动态参数` 和 `静态属性`
        // 先把原来的请求对象 利用lodash深拷贝一下
        // 如果使用同一个goods_cat 之前的级联选择器双向绑定了选中的id 它要求参数必须为数组类型 当前修改转换为字符串 则会报错
        const reqForm = _.cloneDeep(this.addGoodsForm)
        reqForm.goods_cat = reqForm.goods_cat.join(',')
        this.manyParamsList.forEach(item => {
          const manyObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals2.join(' ')
          }
          reqForm.attrs.push(manyObj)
        })
        this.onlyParmasList.forEach(item => {
          const onlyObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          reqForm.attrs.push(onlyObj)
        })
        // 处理完毕 发起请求添加商品
        const { data: res } = await this.$http.post('goods', reqForm)
        if (res.meta.status !== 201)
          return this.$message.error('添加商品失败！')
        console.log(res)
        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId() {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    }
  },
  created() {
    this.getCateList()
  }
}
</script>

<style scoped>
.el-checkbox {
  margin: 0 5px 0 0 !important;
}

.addGoodsBtn {
  margin-top: 15px;
}
</style>
